#!/usr/bin/python
# -*- coding: utf-8 -*-
#
#
#
#

"""
This is the main tester class. It will automatically collect all tests and run
only the tests specified in test_order. They will be run in this order defined
in test_order.
"""

__version__ = '$Id: test.py 164 2008-08-24 19:46:15Z DR0ID $'

import sys
import os
import unittest
import glob
from extern import coverage

# find the local copy
sys.path.insert(0, os.path.join(os.path.dirname(__file__), os.pardir))

# list of all tests, order is important
test_order = [  
                'test_events',
                'test_gamebase',
                'test_pygamegamebase',
                'test_timing'
             ]

COVERAGE_WARNING = \
u"""WARNING: Just because a statement is covered by a test case doesn't mean that
         the test case checks that the statement does the right thing. So it's 
         not a good idea to organize your testing around statement coverage or to 
         set targets for statement coverage. However, coverage testing is a good 
         tool for discovering features that haven't been tested and suggesting 
         profitable new areas to test."""


def my_import(name):
    mod = __import__(name)
    components = name.split('.')
    for comp in components[1:]:
        mod = getattr(mod, comp)
    return mod

def run_tests():
    suites = []
    for testname in test_order:
        module = my_import(testname)
        suites.append(unittest.TestLoader().loadTestsFromModule(module))
    alltests = unittest.TestSuite(suites)
    unittest.TextTestRunner(verbosity=2).run(alltests)

def _get_filenames(root_dir, ext='*.py'):
    src_files = []
    for p, dirs, files in os.walk(root_dir):
        names = glob.glob(os.path.join(p, ext))
        src_files.extend(names)
        count = 0
        for idx, dir in enumerate(list(dirs)):
            if dir.startswith('.'):
                del dirs[idx - count]
                count += 1
            if dir == 'extern':
                del dirs[idx - count]
                count += 1
    return src_files

def main():
    # use the version from the repo
    p = os.path.split(os.path.split(__file__)[0])[0]
    rel_path = os.path.join(p, 'bipy')
    # remove *.pyc and *.pyo files first to make coverage more accurat
    del_names = _get_filenames(rel_path, '*.py?')
    for name in del_names:
        if name.endswith('pyc') or name.endswith('pyo'):
            try:
                os.remove(name)
            except OSError:
                sys.stdout.write(u'ERROR: %s could not be deleted %s' % (name, os.linesep))
    coverage.erase()
    # tests
    coverage.start()
    run_tests()
    coverage.stop()
    # results
    mods = _get_filenames(rel_path)
    sys.stdout.write(u"%s%s%s" % (os.linesep, COVERAGE_WARNING, os.linesep) )
    coverage.report(mods, ignore_errors=0, show_missing=1)

if __name__ == '__main__':
    main()
